#####################################################################
# Product:      KnowledgeEngine (Plone Edition)
#
# File:         Section.py
#
# Copyright:    Copyright (c) 2004, Faulkner Technologies
#
# Author:       Brian Oliver
#
# Description:  This file defines the Section class, a simple
#               Button for placement in Toolbars
#
# See Also:     Element, Toolbar
#####################################################################
#####################################################################
## Knowledge Engine Library Imports
from Products.KnowledgeEngine.Common import *
from Products.KnowledgeEngine.Core import *
from Products.KnowledgeEngine.Elements.TabBar.TabBarTool import TabBarTool, TabBarToolInfo
from Products.KnowledgeEngine.PropertyDefinition import PropertyDefinition
from Products.KnowledgeEngine.PropertyFormats import *
from Products.KnowledgeEngine.PropertyTypes import *
from Products.KnowledgeEngine.PropertyDefinition import *
from Products.KnowledgeEngine.PropertyTypes import *
from Products.KnowledgeEngine.PropertyFormats import *
from Products.KnowledgeEngine.PropertyStructures import *

from Products.KnowledgeEngine.Components.Section.Section import Section, SectionInfo

#####################################################################
## Zope Library Imports
from Globals import DTMLFile
from App.ImageFile import ImageFile

#####################################################################
## Python Library Imports
# (none)

#####################################################################
## Private Functions (global)

def getPages(context):
    """
        Returns a [(name,identity)] of pages within the specified
        context (model).
    """
    #get our model
    model = context.getParentByInstanceOf("Model")
    #return the list of available pages in the model
    return [(page.getTitleOrId(),page.getIdentity()) for page in model.getPages()]

#####################################################################
## SectionInfo Class Definition
class SectionTabInfo(TabBarToolInfo):
    """
        Defines the class info methods, defining information about
        the class without needing an instance of the class
    """
    
    #---------------------------------------------------------------#
    
    def getClassName(self):
        """
            Returns the name of the class for which 
            we are providing information.
        """
        return "SectionTab"

    #---------------------------------------------------------------#
    
    def isInstanceOf(self, className):
        
        return self.getClassName() == className or TabBarToolInfo.isInstanceOf(self, className)
    
    
    #---------------------------------------------------------------#

    def getDisplayName(self):
        """
            Return a friendly name for the class instances
            (this is used for displaying in lists etc)
        """
    
        return "Section Tab"
        
    #---------------------------------------------------------------#

    def getIdentityType(self):
        """
            Return the identity type.  
        """
        
        return "tabSection"
        
    #---------------------------------------------------------------#
    
    def getClassIcon(self):
        """
            Return the appropriate icon file for the class.
        """
        
        return ImageFile('skins/SectionTab_icon.png', globals())
        
    #---------------------------------------------------------------#

    def isPermittedInContainer(self, containerClassInfo, containerInstance = None, instance=None):
        """
            ABSTRACT: Returns if class instances (instance) is permitted in 
            the specified container (containerInstance)
            
            NOTE: This is from this class' instance perspective.
        """
        
        #DEFAULT RULE: Sections are only permitted in TabBars and Models
        return containerClassInfo.isInstanceOf('TabBar')
    
    #---------------------------------------------------------------#

    def onConfigureProperties(self):
        """
            Automatically called by the Knowledge Engine once
            the class has been loaded.  Use this method to register 
            class specific properties using the PropertyReflection interface.
            
            If this class is sub-classed, a call must be made to
            the super-class to ensure super-class properties are
            correctly registered
            
            NOTE: This method is called before ClassInfo.onAfterStartup()            
        """

        #initialise the super-class properties for reflection
        TabBarToolInfo.onConfigureProperties(self)

        #set the default title
        self.getPropertyDefinition('title').setDefaultValue('Section Tab')

        #set the default id
        self.getPropertyDefinition('id').setDefaultValue('tabSection')

       
        #self.addPropertyDefinition(PropertyDefinition(identity="sectionIdentity",
                                                      #displayName="Section Identity",
                                                      #description="The Section Identity to link to",
                                                      #propertyType=pt_STRING,
                                                      #propertyFormat=pf_TEXT_SINGLELINE,
                                                      #defaultValue=""))
                                                      
        def isDisplayable(component):
            return component.isInstanceOf('Section') or component.isInstanceOf('Model')
                                                      
        self.addPropertyDefinition(PropertyDefinition(
            identity='sectionIdentity',
            height="300px",
            singleSelection=true,
            displayName="Section",
            description="Select the section to link to",
            defaultValue="",
            propertyType="L",
            isDisplayableFunction=isDisplayable,
            isSelectableFunction=lambda component: component.isInstanceOf('Section'),
            isInitiallyExpandedFunction=lambda component:true,
            propertyFormat=pf_GENERIC_OBJECT_CHOOSER,
            propertyStructure=ps_ATOMIC
        ))                                                      

        # 20070308 johnm    Removed Tab Title property field in favour of the
        #                   components title (see ticket #659)
        # 
        # self.addPropertyDefinition(PropertyDefinition(identity="tabTitle",
        #                                               displayName="Tab Title",
        #                                               description="The text to display on the tab",
        #                                               propertyType=pt_STRING,
        #                                               propertyFormat=pf_TEXT_SINGLELINE,
        #                                               defaultValue=""))                                                      
      
        #add the 'redirectURL' property        
        #self.addPropertyDefinition(PropertyDefinition(identity="redirectURL", displayName="Post Submit Destination URL", description="The URL the client browser will be directed to after the submit has been completed.  Leave blank for the default (myknowledge) area", propertyType=pt_STRING, propertyFormat=pf_TEXT_SINGLELINE, defaultValue=""))
        
        #add the 'displayOn' property
        #(the property represents a sections on which the button is displayed)
        #self.addPropertyDefinition(PropertyDefinition(identity="displayOn", displayName="Display On...", description="The pages on which this button will be displayed", defaultValue=[], propertyType=pt_STRING, propertyFormat=pf_NATIVE, propertyStructure=ps_LIST, hasEnumeratedValues=true, enumeratedValuesFunction=getPages))

    #---------------------------------------------------------------#

#####################################################################
## Section Class Definition
class SectionTab(TabBarTool):
    """
        A class to represent a button in a toolbar
    """

    #---------------------------------------------------------------#

    #ABSTRACT TRANSIENT: a ClassInfo implementation instance to provide info about this class
    _CLASSINFO = SectionTabInfo()

    #---------------------------------------------------------------#

    def __init__(self, id, identity):
        "Constructor for the Section Tab"        

        TabBarTool.__init__(self, id, identity)
        
        #perform onAfterInstanciation processing
        self.onAfterInstanciation()

    #---------------------------------------------------------------#

    def onAfterInstanciation(self):
        """
            Handle Knowledge Engine specific actions after this object 
            has been loaded into memory.  
            
            This is useful for performing backwards compatibility
        """        
        
        #perform default processing 
        TabBarTool.onAfterInstanciation(self)
        
    #---------------------------------------------------------------#

    def getTabTitle(self):
        """ Returns the title to display on the tab """
        return getattr(self, 'tabTitle', None)


    #---------------------------------------------------------------#

    def getSectionIdentity(self):
        """ Returns the section identity to link to """
        sectionIdentity = self.sectionIdentity
        if type(sectionIdentity) is list:
            return sectionIdentity[0]
        return sectionIdentity
    
    #---------------------------------------------------------------#
    
    def setSectionIdentity(self, value):
        """ Sets the section identity """
        
        self.sectionIdentity = value
    
    #---------------------------------------------------------------#
    
    def isSelected(self, REQUEST):
        """ Determines if this tab is selected based on the passed REQUEST object """
        
        page = REQUEST.get('PAGE',None)
        return page and page.getIdentity() == self.getSectionIdentity()

    #---------------------------------------------------------------#
    def getContent(self, contentZone=None, forGenericObject = None, componentContext = None, assessment = None):
        """
            Return the Element generated 
            content for the specified contentZone (a string).   

            This method is called by the Model.index_html dtml file
            to customise the appearance of the output.
            
            By overriding this method, Elements have the opportunity
            to perform customization of the output from a Model
            during the assessment process.
        """
        
        
        result = ""

        if contentZone == "TABBAR":
            
            klass = self.isSelected(self.REQUEST) and "selected" or "plain"
            
            # HACKHACK- Relying on args passed through REQUEST is a bad idea here!

            
            revision = assessment.getRevision() or assessment.getLatestRevisionNumber()
            
            result += '''
                <li class='%s visualIEFloatFix' style="line-height: 1.2">
                    <a href="javascript:navigateToPage(getPage('%s'))">
                        %s
                    </a>
                </li>
            ''' % (klass, self.getSectionIdentity(), self.getTabTitle() or self.getTitleOrId())

        return result
        
    #---------------------------------------------------------------#

#####################################################################
## Class Initialisation

# Register Class Information with the Knowledge Engine
registerGenericObjectClass(SectionTab)

#####################################################################

